/*
 * Generated function Class.
 */
package HDFSTest;

import java.util.Arrays;

import org.simgrid.msg.Host;
import org.simgrid.msg.Msg;
import org.simgrid.msg.MsgException;
import org.simgrid.msg.Process;
import org.simgrid.msg.Task;

public class FileRequester extends Process {
	private String[] files;
	private boolean[] writeOrRead;
	private long[] locs;

	/**
	 * Default constructor for Processes needs to be used as part of framework.
	 * 
	 * @param host
	 * @param name
	 * @param args
	 */
	public FileRequester(Host host, String name, String[] args) {
		super(host, name, args);
	}

	/**
	 * Requiers override of main needed to write a Process. Gets required files, whether to read/write, and block locations
	 * from args, and then sends Tasks to get the needed files.
	 */
	public void main(String[] args) throws MsgException {
		Msg.info("FileRequester start");
		files = args[0].split(",");// args specified in Deployment xml file
		String[] toWriteOrRead = args[1].split(",");
		writeOrRead = new boolean[toWriteOrRead.length];
		for (int i = 0; i < writeOrRead.length; i++)
			writeOrRead[i] = Boolean.valueOf(toWriteOrRead[i]);
		String[] stringBlocks = args[2].split(",");
		locs = new long[stringBlocks.length];
		for (int i = 0; i < stringBlocks.length; i++)
			locs[i] = Long.parseLong(stringBlocks[i]);
		// go through each file and do read/write
		for (int i = 0; i < files.length; i++) {
			Msg.info("requesting " + files[i]);// logging
			FileRequest request = new FileRequest(this.getHost().getName(), writeOrRead[i], files[i]);
			request.send(HDFS.class.getName());// sending request for file to HDFS
			request = (FileRequest) Task.receive(this.getHost().getName(), Host.getByName(HDFS.class.getName()));
			while (request == null) {// loop waiting for response
				Msg.info("Trying to get response for " + files[i]);
				try {
					request = (FileRequest) Task.receive(this.getHost().getName(), 0.5);
				} catch (Exception e) {// needed for timeout (time quanta need figuring out)
					e.printStackTrace();
					break;
				}
			}
			Msg.info("Received response " + Arrays.toString(request.getResponse()));
			// FileRequest.getResponse has names of data nodes to get/read files
			if (request != null && request.getResponse() != null) {
				for (String name : request.getResponse()) {
					IORequest ioRequest = new IORequest(this.getHost().getName(), 0, writeOrRead[i], files[i],
							new FileBlock(locs[i]));
					ioRequest.send(name);// sending IO request to right location
				}
			}
		}
		Msg.info("FileRequester exit");
	}
}
